# -*- encoding: utf-8 -*-
from src.ApiTest.SqlData.Database.sql_database import SqlData, SqlSchema
from src.User.Database.user_database import User, UserSchema
from Common.yaml_method import YamlMethod
from sqlalchemy import and_
import ast


class SqlList:
    """
    获取SQL配置列表接口
    """

    @staticmethod
    def sql_list(page, limit, user_id, config_name, project_id):
        """
        获取SQL配置列表接口
        :param page: 页码
        :param limit: 每页多少条数据
        :param user_id: user_id
        :param config_name: 配置名称
        :param project_id: 项目ID
        :return:
        """

        code = YamlMethod().read_data('code.yaml')['code']

        if project_id:
            if config_name:
                # projectId和config_name都不为空
                data = SqlData.query.filter_by(configName=config_name, projectId=project_id)\
                    .paginate(page=page, per_page=limit)
            else:
                # projectId不为空，config_name都为空
                data = SqlData.query.filter_by(projectId=project_id).paginate(page=page, per_page=limit)
        else:
            # 先查询用户所属项目信息
            user = User.query.filter_by(id=user_id).first()
            user_schema = UserSchema()
            user_data = user_schema.dump(user)
            user_project_id = user_data['user_projects']
            id_list = ast.literal_eval(user_project_id)
            # 开始构建过滤条件
            filters = [SqlData.projectId.in_(id_list)]
            if config_name:
                # projectId为空，config_name不为空
                filters.append(SqlData.configName == config_name)
                data = SqlData.query.filter(and_(*filters)).paginate(page=page, per_page=limit)
            else:
                # projectId和config_name都为空
                data = SqlData.query.filter(SqlData.projectId.in_(id_list)).paginate(page=page, per_page=limit)

        info = []
        if data:
            for i in data.items:
                mysql_schema = SqlSchema()
                mysql_data = mysql_schema.dump(i)
                # 将单条信息添加到info中
                info.append(mysql_data)

        total = data.total
        has_more = data.has_next

        res = {
            'code': code[0],
            'message': 'success',
            'data': {
                'sqlList': info,
                'total': total,
                'has_more': has_more
            }
        }

        return res


